package com.example.demo.snowflake.util;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname IdGeneratorSnowflake
 * @description
 * @date 2022/12/22 14:47
 * <p>
 * ******************************************************
 */

import cn.hutool.core.lang.Singleton;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Component
public class IdGeneratorSnowflake {
    private long workerId = 0;
    private long datacenterId = 1;
    private Snowflake snowflake = Singleton.get(Snowflake.class, workerId, datacenterId, true);

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    public static void main(String[] args) {
        IdGeneratorSnowflake idGenerator = new IdGeneratorSnowflake();
        System.out.println(idGenerator.snowflakeId());

        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 1; i <= 20; i++) {
            threadPool.submit(() -> {
                System.out.println(idGenerator.snowflakeId());
            });
        }

        threadPool.shutdown();

    }
}

